//
//  ZDPhotoBrowserViewController.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/8.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDPhotoBrowserViewController.h"
#import "UILabel+Extension.h"
#import "UIButton+Extension.h"
#import "ZDPhotoBrowserCell.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "ZDPhotoBrowserModel.h"
#import "ZDPBModalAnimation.h"
#import "ZDPBDismissAnimation.h"
#import "UIImage+ZDScaleImage.h"

#define ZDPadding 10

@interface ZDPhotoBrowserViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UIViewControllerTransitioningDelegate, ZDPhotoBrowserCellDelegate>

@property (nonatomic, assign) NSUInteger index;

@property (nonatomic, strong) NSArray *models;

@property (nonatomic, strong) UILabel *indicatorLabel;

@property (nonatomic, strong) UIButton *closeBtn;

@property (nonatomic, strong) UIButton *saveBtn;

@property (nonatomic, strong) UIView *bkgView;

@end

@implementation ZDPhotoBrowserViewController

///快捷创建对象
+ (instancetype)photoBrowserViewControllerWithIndex:(NSUInteger)index models:(NSArray *)models
{
    ZDPhotoBrowserViewController *vc = [[self alloc] init];
    
    vc.index = index;
    
    vc.models = models;
    
    return vc;
}


static NSString *reuseIdentifier = @"ZDPhotoBrowserCell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    [self prepareUI];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.index inSection:0];
    
    [self.photoBrowserCollectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}


///准备UI
- (void)prepareUI
{
    //添加子控件
    [self.view addSubview:self.bkgView];
    [self.view addSubview:self.photoBrowserCollectionView];
    [self.view addSubview:self.indicatorLabel];
    [self.view addSubview:self.closeBtn];
    [self.view addSubview:self.saveBtn];
    
//    self.photoBrowserCollectionView.translatesAutoresizingMaskIntoConstraints = NO;
    self.indicatorLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.closeBtn.translatesAutoresizingMaskIntoConstraints = NO;
    self.saveBtn.translatesAutoresizingMaskIntoConstraints = NO;
    
    //设置frame
    self.bkgView.frame = self.view.bounds;
    
    //添加约束
    NSDictionary *views = @{
                        @"pbcv": self.photoBrowserCollectionView,
                        @"il": self.indicatorLabel,
                        @"cb": self.closeBtn,
                        @"sb": self.saveBtn
                        };
    
    //photoBrowserCollectionView
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[pbcv]-0-|" options:0 metrics:nil views:views]];
//    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[pbcv]-0-|" options:0 metrics:nil views:views]];
    
    self.photoBrowserCollectionView.frame = CGRectMake(0, 0, ZDScreenSize.width + ZDPadding, ZDScreenSize.height);
    
    
    //indicatorLabel
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_indicatorLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_indicatorLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeTop multiplier:1.0 constant:20]];
    
    //closeBtn
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[cb(35)]-10-|" options:0 metrics:nil views:views]];
    
    //saveBtn
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[sb(35)]-10-|" options:0 metrics:nil views:views]];
    
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[cb(75)]-(>=0)-[sb(75)]-10-|" options:0 metrics:nil views:views]];
    
    
    [self setPhotoBrowserCollectionView];
}


//设置PhotoBrowserCollectionView
- (void)setPhotoBrowserCollectionView
{
    self.photoBrowserCollectionView.backgroundColor = [UIColor clearColor];
    
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.photoBrowserCollectionView.collectionViewLayout;
    
    layout.itemSize = CGSizeMake(ZDScreenSize.width, ZDScreenSize.height);
    layout.minimumLineSpacing = ZDPadding;
    layout.minimumInteritemSpacing = ZDPadding;
    
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, ZDPadding);
    
    //设置滚动方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    //设置分页
    self.photoBrowserCollectionView.pagingEnabled = YES;
    
    //取消水平滚动条
    self.photoBrowserCollectionView.showsHorizontalScrollIndicator = NO;
    
    //取消弹簧效果
    self.photoBrowserCollectionView.bounces = NO;
    
    //注册cell
    [self.photoBrowserCollectionView registerClass:[ZDPhotoBrowserCell class] forCellWithReuseIdentifier:reuseIdentifier];
}

#pragma mark - 按钮点击事件
- (void)closeBtnClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//保存图片
- (void)saveBtnClick
{
    //获取当前显示的cell
    NSIndexPath *indexPath = [[self.photoBrowserCollectionView indexPathsForVisibleItems] firstObject];
    
    ZDPhotoBrowserCell * cell = (ZDPhotoBrowserCell *)[self.photoBrowserCollectionView cellForItemAtIndexPath:indexPath];
    
    UIImage *image = cell.imageView.image;
    
    //保存到相册
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error)
    {
        [SVProgressHUD showErrorWithStatus:@"保存失败" maskType:SVProgressHUDMaskTypeBlack];
        
        return;
    }
    
    [SVProgressHUD showSuccessWithStatus:@"保存成功" maskType:SVProgressHUDMaskTypeBlack];
}


#pragma mark - 数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.models.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZDPhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    if (!cell.delegate)
    {
        cell.delegate = self;
    }
    
//    cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1.0];
    
    cell.backgroundColor = [UIColor clearColor];
    
    ZDPhotoBrowserModel *model = self.models[indexPath.item];
    
//    cell.url = model.url;
    cell.model = model;
    
    return cell;
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSIndexPath *indexPath = self.photoBrowserCollectionView.indexPathsForVisibleItems.firstObject;
    
    self.indicatorLabel.text = [NSString stringWithFormat:@"%ld / %ld", indexPath.item + 1, self.models.count];
}


#pragma mark - 转场动画代理方法
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return [[ZDPBModalAnimation alloc] init];
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return [[ZDPBDismissAnimation alloc] init];
}


#pragma mark - 转场动画相关方法
//返回modal过渡视图
- (UIImageView *)modalTempImageView
{
    //首先获取点击的缩略图(微博配图)
    ZDPhotoBrowserModel *model = self.models[self.index];
    UIImageView *thumbImageView = model.imageView;
    
    //创建过渡视图
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:thumbImageView.image];
    
    //设置frame 注意需要转换坐标系
    tempImageView.frame = [thumbImageView.superview convertRect:thumbImageView.frame toCoordinateSpace:self.view];
    
    //同微博缩略图一样 设置相关属性
    tempImageView.contentMode = UIViewContentModeScaleAspectFill;
    tempImageView.clipsToBounds = YES;
    
    return tempImageView;
}

//返回过渡视图最终的frame
- (CGRect)modalTempViewEndFrame
{
    //首先获取点击的缩略图(微博配图)
    ZDPhotoBrowserModel *model = self.models[self.index];
    UIImageView *thumbImageView = model.imageView;
    
    //取出对应的缩略图片
    UIImage *image = thumbImageView.image;
    
    //计算放大到屏幕宽度后的size
    CGSize newSize = image.disPlaySize;
    
    if (newSize.height < ZDScreenSize.height)
    {
        return CGRectMake(0, (ZDScreenSize.height-newSize.height) * 0.5, newSize.width, newSize.height);
    }
    else
    {
        return CGRectMake(0, 0, newSize.width, ZDScreenSize.height);
    }
}

//返回dismiss过渡视图
- (UIImageView *)dismissTempImageView
{
    NSIndexPath *indexPath = [[self.photoBrowserCollectionView indexPathsForVisibleItems] firstObject];
    
    //获取当前cell
    ZDPhotoBrowserCell *cell = (ZDPhotoBrowserCell *)[self.photoBrowserCollectionView cellForItemAtIndexPath:indexPath];
    
    //创建过渡视图
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:cell.imageView.image];
    
    //同微博缩略图一样 设置相关属性
    tempImageView.contentMode = UIViewContentModeScaleAspectFill;
    tempImageView.clipsToBounds = YES;
    
    tempImageView.frame = [cell.imageView.superview convertRect:cell.imageView.frame toCoordinateSpace:self.view];
    
    return tempImageView;
}


//返回过渡视图最终的frame
- (CGRect)dismissTempViewEndFrame
{
    //当前可见cell的indexPath
    NSIndexPath *indexPath = [[self.photoBrowserCollectionView indexPathsForVisibleItems] firstObject];
    
    //根据索引取出对应的缩略图
    ZDPhotoBrowserModel *model = self.models[indexPath.item];
    UIImageView *thumbImageView = model.imageView;
    
    CGRect rect = [thumbImageView.superview convertRect:thumbImageView.frame toCoordinateSpace:self.view];
    
    return rect;
}


#pragma mark - ZDPhotoBrowserCellDelegate代理方法
- (UIView *)viewForTransparent
{
    return self.bkgView;
}

- (void)dismiss
{
    [self dismissViewControllerAnimated:NO completion:nil];
}


#pragma mark 懒加载
- (UICollectionView *)photoBrowserCollectionView
{
    if (!_photoBrowserCollectionView)
    {
        _photoBrowserCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
        
        _photoBrowserCollectionView.dataSource = self;
        _photoBrowserCollectionView.delegate = self;
    }
    
    return _photoBrowserCollectionView;
}

- (UILabel *)indicatorLabel
{
    if (!_indicatorLabel)
    {
        _indicatorLabel = [[UILabel alloc] initWithFontSize:18 color:[UIColor whiteColor]];
        
        _indicatorLabel.text = [NSString stringWithFormat:@"%ld / %ld", self.index + 1, self.models.count];
    }
    
    return _indicatorLabel;
}

- (UIButton *)closeBtn
{
    if (!_closeBtn)
    {
        _closeBtn = [[UIButton alloc] initWithTitle:@"关闭" bkgImageName:@"health_button_orange_line" titleColor:[UIColor whiteColor] fontSize:18];
        
        [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _closeBtn;
}

- (UIButton *)saveBtn
{
    if (!_saveBtn)
    {
        _saveBtn = [[UIButton alloc] initWithTitle:@"保存" bkgImageName:@"health_button_orange_line" titleColor:[UIColor whiteColor] fontSize:18];
        
        [_saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _saveBtn;
}

- (UIView *)bkgView
{
    if (!_bkgView)
    {
        _bkgView = [[UIView alloc] init];
        
        _bkgView.backgroundColor = [UIColor blackColor];
    }
    
    return _bkgView;
}

@end
